package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.json.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.homeservicemanagementsystem.config.GiteeConstants;
import com.heima.homeservicemanagementsystem.config.annotation.RestControllerMapping;
import com.heima.homeservicemanagementsystem.entity.giteeInfo;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.service.GiteeLoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

/**
 * @Description
 * @Author jcf
 * @Date 2025/3/8
 */
@AllArgsConstructor
@RestControllerMapping("/auth")
@Tag(name = "gitee登录操作")
public class giteeLoginController {
    private static final Logger log = LoggerFactory.getLogger(giteeLoginController.class);
    private final GiteeConstants giteeConstants;
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private GiteeLoginService giteeLoginService;

    /**
     * 获得跳转到Gitee登录页的url,前台直接a连接访问
     *
     * @return
     */
    @SaIgnore
    @GetMapping("/gitee/login")
    @Operation(summary = "gitee进行授权")
    public Result getGiteeCode() {
        String authurl = giteeLoginService.getAuth();

        return Result.success("操作成功", authurl);
    }

    @SaIgnore
    @PostMapping("/gitAccessToken")
    @Operation(summary = "获取gitee的gitAccessToken")
    public Result gitAccessToken(@RequestParam String code) {

        return giteeLoginService.getGitAccessToken(code);

    }

    @SaIgnore
    @GetMapping("/getGiteeUserInfoAndLogin")
    @Operation(summary = "获取用户的信息及登录接口")
    public Result getGiteeUserInfo(@RequestParam String accessToken) throws JsonProcessingException {
        log.info("用户的accesstoken：{}", accessToken);
        giteeInfo giteeUserInfo = giteeLoginService.getGiteeUserInfo(accessToken);

        return giteeLoginService.giteeLogin(giteeUserInfo);
    }

    @SaIgnore
    @GetMapping("/refashToken")
    @Operation(summary = "刷新AccessToken")
    public Result refashToken(@RequestParam String refresh_token) throws JsonProcessingException {
        return giteeLoginService.refashToken(refresh_token);
    }

}
